package com.wanghang89.gmail.util.db;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;

public abstract class BaseDbUtils {
	
	protected JdbcTemplate jdbcTemplate;
	
	protected final static ResultSetExtractor<Long> GET_FIRST_LONG_EXTRACTOR = new ResultSetExtractor<Long>() {
		@Override
		public Long extractData(ResultSet rs) throws SQLException,
				DataAccessException {
			while (rs.next()) {
				LOGGER.debug("get first long from result:"+rs.getLong(1));
				return rs.getLong(1); 
			}
			LOGGER.debug("result no data.");
			return 0l;
		}
	};
	
	private final static Logger LOGGER = Logger.getLogger(BaseDbUtils.class);

	protected Long add(String sql ,Object[] params) throws DBException 
	{
		return jdbcTemplate.execute(new AddPreparedStatementCreator(sql,Statement.RETURN_GENERATED_KEYS)
										,new AddPreparedStatementCallback(params));
	}
	
	protected boolean addBatch(String sql , Object[][] params) throws DBException 
	{
		LOGGER.debug("sql:"+sql);
		return jdbcTemplate.execute(new AddPreparedStatementCreator(sql,Statement.RETURN_GENERATED_KEYS)
										, new AddBatchPreparedStatementCallback(params));
	}

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

}

